package com.example.testdemoutils.dynamic_data_source.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.testdemoutils.dynamic_data_source.dao.DatasourceDao;
import com.example.testdemoutils.dynamic_data_source.exception.RRException;
import com.example.testdemoutils.dynamic_data_source.po.DynamicDataSourceModel;
import com.example.testdemoutils.dynamic_data_source.utils.ConfigConstant;
import com.example.testdemoutils.dynamic_data_source.utils.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据源缓存池
 */
public class DataSourceCachePool {
    /**
     * 数据源连接池缓存【本地 class缓存 - 不支持分布式】
     */
    private static Map<String, DruidDataSource> dbSources = new HashMap<>();
    private static RedisTemplate<String, Object> redisTemplate;

    private static RedisTemplate<String, Object> getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate<String, Object>) SpringContextUtils.getBean("redisTemplate");
        }
        return redisTemplate;
    }

    /**
     * 获取多数据源缓存
     *
     * @param dbKey
     * @return
     */
    public static DynamicDataSourceModel getCacheDynamicDataSourceModel(String dbKey) {
//        String redisCacheKey = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY + dbKey;
//        if (Boolean.TRUE.equals(getRedisTemplate().hasKey(redisCacheKey))) {
//            String model = (String) getRedisTemplate().opsForValue().get(redisCacheKey);
//            return JSON.parseObject(model, DynamicDataSourceModel.class);
//        }
        DatasourceDao datasourceDao = (DatasourceDao) SpringContextUtils.getBean("datasourceDao");
        DynamicDataSourceModel dbSource = datasourceDao.getDynamicDbSourceByCode(dbKey);
        try {
//            dbSource.setDbPassword(AesUtil.decryptBySalt(dbSource.getDbPassword(),dbSource.getId()));
            dbSource.setDbPassword(dbSource.getDbPassword());
        } catch (Exception e) {
            throw new RRException("动态数据源密钥解密失败，dbKey：" + dbKey);
        }

//        if (dbSource != null) {
//            getRedisTemplate().opsForValue().set(redisCacheKey, JSONObject.toJSONString(dbSource));
//        }
        return dbSource;
    }

    public static DruidDataSource getCacheBasicDataSource(String dbKey) {
        return dbSources.get(dbKey);
    }

    /**
     * put 数据源缓存
     *
     * @param dbKey
     * @param db
     */
    public static void putCacheBasicDataSource(String dbKey, DruidDataSource db) {
        dbSources.put(dbKey, db);
    }

    /**
     * 清空数据源缓存
     */
    public static void cleanAllCache() {
        //关闭数据源连接
        for (Map.Entry<String, DruidDataSource> entry : dbSources.entrySet()) {
            String dbkey = entry.getKey();
            DruidDataSource druidDataSource = entry.getValue();
            if (druidDataSource != null && druidDataSource.isEnable()) {
                druidDataSource.close();
            }
            //清空redis缓存
            getRedisTemplate().delete(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY + dbkey);
        }
        //清空缓存
        dbSources.clear();
    }

    public static void removeCache(String dbKey) {
        //关闭数据源连接
        DruidDataSource druidDataSource = dbSources.get(dbKey);
        if (druidDataSource != null && druidDataSource.isEnable()) {
            druidDataSource.close();
        }
        //清空redis缓存
        getRedisTemplate().delete(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY + dbKey);
        //清空缓存
        dbSources.remove(dbKey);
    }

}

